<template>
  <!-- :close-on-click-modal="false" //禁用点击空白区域
  :close-on-press-escape="false" //禁用ESC键 -->
  <el-dialog
    :title="!userId ? '新增' : '修改'"
    :close-on-press-escape="false" 
    :close-on-click-modal="false"
    :append-to-body="true"
    :lock-scroll="true"
    :visible.sync="visible">

    <el-upload 
      class="upload-demo" 
      :ref="file" 
      :show-file-list="true" 
      :auto-upload="false" 
      :headers='token'
      :with-credentials="true" 
      :drag="true" 
      action="http://192.168.43.102:8081/student/comwenxian"
      :on-success="uploadSuccess" 
      :before-upload="beforeUpload">
      <!-- accept="*" -->
      <!-- :data="dataForm" -->
      <!-- :headers='token' -->
      <!-- :on-remove="handleRemove"
                        :on-exceed="handleExceed"
                        :on-remove="handleRemove"
                        :on-change="changeFile"
                        :on-error="error"
                        :before-remove="beforeRemove" -->
      <!-- <el-button size="middle" type="primary" icon="el-icon-upload2">上传文件</el-button> -->
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传docx文件,文件大小不超过20M</div>
    </el-upload>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from '@/utils/validate'
import servicesApi from '@/services/servicesApi';
import { getDictDataList } from '@/utils';
export default {
  data() {
    let validatePassword = (rule, value, callback) => {
      if (!this.dataForm.name && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    let validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.name && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    let validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      state: 3,
      departmentDict: {},
      userId: 0,
      stateList: [
        { state: 3, stateName: '管理员' },
        { state: 2, stateName: '教师' },
        { state: 1, stateName: '学生' },
      ],
      dataForm: {//新增用户时
        username: '2020110228',
        name: 'ldq',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        department: '',
        email: '1927470557@qq.com',
        phone: '13982677074',
        state: 1,
        sex: '男',
        status: 1
      },
      AdataForm: {
        //用户表
        userId: 0,
        name: 'ldq',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        //管理员表
        adId: 1,
        phone: '13982677074',
        email: '1927470557@qq.com',
        sex: '男',
        wx: '',
        department: '',
        status: 0, //0:禁用,1正常
        state: 3, //用户角色 学生1 老师2 管理员3
      },
      SdataForm: {
        //用户表
        userId: 0,
        username: '2020110227',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        state: 1,
        status: 0,
        //学生表
        // eslint-disable-next-line camelcase
        stu_id: '',
        // eslint-disable-next-line camelcase
        stu_role: 1, //用户角色 学生1 老师2 管理员3
        stuName: 'run',
        stuDepartment: '计算机科学',
        stuProfessional: '软件工程',
        stuPhone: '13982677074',
        stuMail: '1927470557@qq.com',
        stuClass: '2020级3班',
        stuSex: '男',
        stuWx: '',
        stuQq: '',
        stuTitle: '',
      },
      TdataForm: {
        //用户表
        userId: 0,
        username: '',
        password: 'Admin1234',
        comfirmPassword: 'Admin1234',
        state: 2, //用户角色 学生1 老师2 管理员3
        status: 0, //0禁用，1正常

        //教师表
        teaSex: '男',
        teaWx: '',
        teaRecord: '硕士',
        teaPost: '教授',
        teaName: 'delete老师',
        teaPhone: '13982677074',
        teaDepartment: '计算机科学学院',
        teaEmail: '1927470557@qq.com',
      },
      dataRule: {
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    getDictList(dictType) {
      let list = getDictDataList(dictType)
      // // console.log(list)
      return list
    },
    init(userId) {
      
      // console.log(userId)
      this.userId = userId || 0 //高级语法
      let arrObj = window.SITE_CONFIG['dictList'].filter((item, index, arr) => { 
        // // console.log(item)
        return item.dictName == '院系' 
      })
      this.departmentDict = arrObj[0].dataList
      // // console.log(this.departmentDict)
      this.visible = true
      // 当数据被修改后使用这个方法，会回调获取更新后的dom再渲染出来
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].resetFields()
      // })
      // servicesApi.getFlagList().then(res => {
      //   if (res.data.code === 200) {
      //     this.stateList = res.data.data //获取身份列表：学生、教师、管理员
      //     this.visible = true
      //     this.$nextTick(() => {
      //       this.$refs['dataForm'].resetFields()
      //     })
      //   }
      // })

      if (this.userId) { //修改用户
        // console.log('修改用户')
        if (state == 3) {
          this.AdataForm.userId=this.userId
          this.AdataForm.state=this.state
          // console.log(this.AdataForm)
        } else if (state==2) {
          this.TdataForm.userId = this.userId
          this.TdataForm.state = this.state
        } else {
          this.SdataForm.userId = this.userId
          this.SdataForm.state = this.state
        }
        servicesApi.getUserById(this.userId).then(res => {
          let code = res.data.code
          let data = res.data.data
          // console.log('查询用户信息')
          if (code === 200) {
            // console.log(state)
            // console.log(data)
            if (state==3) {
              this.AdataForm =  data
              // console.log(this.AdataForm)
            } else if (state==2) {
              // this.TdataForm = { state: 2, ...data }
              this.TdataForm= data
              // console.log(this.TdataForm)
            } else {
              // this.SdataForm = { state: 1, ...data }
              this.SdataForm = data
              // console.log(this.SdataForm)
            }
          }
        })
      } else { //新增用户
        // console.log('新增用户')
      }
      

      // this.AdataForm.name = name || 0
      // this.$http({
      //   url: this.$http.adornUrl('/sys/role/select'),
      //   method: 'get',
      //   params: this.$http.adornParams()
      // }).then(({data}) => {
      //   this.roleList = data && data.code === 0 ? data.list : []
      // }).then(() => {
      //   this.visible = true
      //   this.$nextTick(() => {
      //     this.$refs['AdataForm'].resetFields()
      //   })
      // }).then(() => {
      //   if (this.AdataForm.name) {
      //     this.$http({
      //       url: this.$http.adornUrl(`/sys/user/info/${this.AdataForm.name}`),
      //       method: 'get',
      //       params: this.$http.adornParams()
      //     }).then(({data}) => {
      //       if (data && data.code === 0) {
      //         this.AdataForm.name = data.user.name
      //         this.AdataForm.salt = data.user.salt
      //         this.AdataForm.email = data.user.email
      //         this.AdataForm.phone = data.user.phone
      //         this.AdataForm.roleIdList = data.user.roleIdList
      //         this.AdataForm.status = data.user.status
      //       }
      //     })
      //   }
      // })
    },
    dataFormSubmit() {
      // this.$message({
      //   message: '操作成功',
      //   type: 'success',
      //   duration: 1500,
      //   onClose: () => {
      //     this.visible = false
      //     this.$emit('refreshDataList')
      //   }
      // })
      
      
      if (this.userId) {//修改
        if (this.state==3) {
          this.$refs['AdataForm'].clearValidate() // 移除表单项的校验结果
          servicesApi.updateUserA(this.AdataForm).then(res => {
            let code = res.data.code
            // console.log(code)
            if (code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                  
                }
              })
            } else {
              this.$message.error(res.data.msg)
            }
          })
        } else if (this.state==2) {
          this.$refs['TdataForm'].clearValidate() // 移除表单项的校验结果
          servicesApi.updateUserT(this.TdataForm).then(res => {
            let code = res.data.code
            if (code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                  
                }
              })
            } else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$refs['SdataForm'].clearValidate() // 移除表单项的校验结果
          servicesApi.updateUserS(this.SdataForm).then(res => {
            let code = res.data.code
            if (code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
        
        
      } else { //新增
        this.$refs['dataForm'].clearValidate() // 移除表单项的校验结果
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            servicesApi.addUser(this.dataForm).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }

          // this.$http({
          //   url: this.$http.adornUrl(`/sys/user/${!this.AdataForm.name ? 'save' : 'update'}`),
          //   method: 'post',
          //   data: this.$http.adornData({
          //     'userId': this.AdataForm.name || undefined,
          //     'name': this.AdataForm.name,
          //     'password': this.AdataForm.password,
          //     'salt': this.AdataForm.salt,
          //     'email': this.AdataForm.email,
          //     'phone': this.AdataForm.phone,
          //     'status': this.AdataForm.status,
          //     'roleIdList': this.AdataForm.roleIdList
          //   })
          // }).then(({data}) => {
          //   if (data && data.code === 0) {
          //     this.$message({
          //       message: '操作成功',
          //       type: 'success',
          //       duration: 1500,
          //       onClose: () => {
          //         this.visible = false
          //         this.$emit('refreshDataList')
          //       }
          //     })
          //   } else {
          //     this.$message.error(data.msg)
          //   }
          // })
        })
      }
      
    }
  }
}
</script>
